package com.atos.optical.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.atos.optical.Enums.ResponseCodeEnum;
import com.atos.optical.Enums.StaticEnums;
import com.atos.optical.common.ApiResult;
import com.atos.optical.utils.CacheUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wanghra
 * @version 1.0
 * @description token拦截器，mvc接收请求全局验证token
 * @date 2025/8/11
 */
public class TokenInterceptor implements HandlerInterceptor {
    /**
     * 在业务处理器处理请求之前被调用。预处理，可以进行编码、安全控制、权限校验等处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(StaticEnums.TOKEN_HEADER);
        if (StrUtil.isBlank(token) || !CacheUtil.isExist(token)) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(new ApiResult<>(ResponseCodeEnum.TOKEN_FAIL), JSONWriter.Feature.WriteNulls));
            return false;
        }
        // 每次调用刷新token保留时间
        CacheUtil.put(token, CacheUtil.get(token));
        return true;
    }

    /**
     * 在业务处理器处理请求执行完成后，生成视图之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 在DispatcherServlet完全处理完请求后被调用，可用于清理资源等
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
